package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Student;
import com.itheima.service.ClazzService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author liuyp
 * @since 2025/7/25
 */
@Service
public class ClazzServiceImpl implements ClazzService {
    @Resource
    private ClazzMapper clazzMapper;
    @Resource
    private StudentMapper studentMapper;

    @Override
    public PageBean<Clazz> page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        //1. 开启分页
        PageHelper.startPage(page, pageSize);
        //2. 查询列表
        List<Clazz> list = clazzMapper.page(name, begin, end);
        //   结果列表里有班级信息、班主任名称，但没有status，需要根据班级的开课与结课时间判断此班级当前的状态
        LocalDate today = LocalDate.now();
        for (Clazz clazz : list) {
            if (today.isBefore(clazz.getBeginDate())) {
                //如果当前日期 还没有到 开班日期：说明此班级未开班
                clazz.setStatus("未开班");
            } else if (today.isAfter(clazz.getEndDate())) {
                //如果当前日期 已经过了 结课日期：说明此班级已结课
                clazz.setStatus("已结课");
            }else{
                //否则：此班级已开班、未结课
                clazz.setStatus("已开班");
            }
        }
        //3. 封装结果
        Page<Clazz> p = (Page<Clazz>) list;
        return new PageBean<>((int) p.getTotal(), list);
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    public void updateById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        //判断此班级是否有学生。如果有，就抛异常：不允许删除
        Student student = studentMapper.selectOneByClazzId(id);
        if (student != null) {
            throw new BusinessException("该班级下有学生, 不能直接删除");
        }

        //删除班级
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> queryAll() {
        return clazzMapper.selectAll();
    }
}
